<?php

namespace App\Http\Controllers\Admin;
use App\Models\Admin\DepositOut;
use App\Models\Admin\Order;
use App\Models\Admin\PosOrder;
use App\Models\Admin\Tools;
use App\Models\Admin\Withdraw;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class IndexController extends CommonController {

	public function __construct()
	{
		parent::__construct();
		$this->checkLogin();
	}

	/**
	 * 后台首页整体框架
	 */
	public function index()
	{
        //		$info = array(
//			'操作系统' => PHP_OS,
//			'运行环境' => $_SERVER["SERVER_SOFTWARE"],
//			'PHP运行方式' => php_sapi_name(),
//			'PHP版本' => phpversion(),
//			'程序版本' => 'Laravel 5.4.9',
//			'上传附件限制' => ini_get('upload_max_filesize'),
//			'执行时间限制' => ini_get('max_execution_time') . "s",
//			'剩余空间' => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
//		);
		return view('admin.index.index');
	}

	/**
	 * 后台首页
	 */
	public function main()
	{
        $sid = $_SESSION['node_id'];//关联用户ID
        $uid = $_SESSION['admin_uid'];
        //TODO  加入二分钟缓存
        if(Cache::has('homedata_'.$uid)){
            $data=Cache::get('homedata_'.$uid);
        }else{
            $todayZero=date('Y-m-d 00:00:00');//今日0点
            $todayNow=date('Y-m-d H:i:s');//现在时间
            $sevenDayAgo = date("Y-m-d 00:00:00", strtotime("-7 days"));
            $aMonthAgo=date('Y-m-d 00:00:00',strtotime('-30 days'));
            $mobileModel=new Order();
            $posModel=new PosOrder();
            $withDraw = new Withdraw();

            $data['mobileOrderNum']=$mobileModel->getOrderNumByTimeRange($uid,$todayZero,$todayNow);
            $data['mobileOrderNum']=empty($data['mobileOrderNum'])?0:array_pop($data['mobileOrderNum']);//手机支付今日订单量
            $data['mobileOrderAmount']=$mobileModel->getOrderPayAmountByTimeRange($uid,$todayZero,$todayNow);//手机支付今日营业额
            $data['mobileOrderAmount']=empty($data['mobileOrderAmount'])?0:array_pop($data['mobileOrderAmount']);

            $data['posOrderNum']=$posModel->getOrderNumByTimeRange($sid,$todayZero,$todayNow);
            $data['posOrderNum']=empty($data['posOrderNum'])?0:array_pop($data['posOrderNum']);//POS机支付今日订单量
            $data['posOrderAmount']=$posModel->getOrderPayAmountByTimeRange($sid,$todayZero,$todayNow);
            $data['posOrderAmount']=empty($data['posOrderAmount'])?0:array_pop($data['posOrderAmount']);//POS机今日营业额

            $data['mobileCashed']=$withDraw->getCashed($sid,1);//手机支付已提现
            $data['mobileCanCash']=$mobileModel->getRealIncome($uid)-$data['mobileCashed'];//手机支付可提现余额

            $data['posCashed']=$withDraw->getCashed($sid,2);//POS机支付已提现
            $data['posCanCash']=$posModel->getRealIncome($sid)- $data['posCashed'];//POS机支付可提现余额

            $data['depositCashed']= $withDraw->getCashed($sid, 3);//让利存款已提现
            $data['depositCanCash']=with(new DepositOut())->getUnfreeze($sid)-$data['depositCashed'];//让利存款可提现余额

            $xAxis7=Tools::getEveryDay(7,time());
            $xAxis30=Tools::getEveryDay(30,time());
            $data['lists7']=json_encode([
                'xAxis'=>$xAxis7,
                'mobile'=>Tools::getEveryDayVal($xAxis7,$mobileModel->getOrderPayAmountByTimeRange($uid,$sevenDayAgo,$todayNow)),
                'pos'=>Tools::getEveryDayVal($xAxis7,$posModel->getOrderPayAmountByTimeRange($sid,$sevenDayAgo,$todayNow))
            ]);//最近7天数据
            $data['lists30']=json_encode([
                'xAxis'=>$xAxis30,
                'mobile'=>Tools::getEveryDayVal($xAxis30,$mobileModel->getOrderPayAmountByTimeRange($uid,$aMonthAgo,$todayNow)),
                'pos'=>Tools::getEveryDayVal($xAxis30,$posModel->getOrderPayAmountByTimeRange($sid,$aMonthAgo,$todayNow)),
            ]);//最近30天数据
            Cache::put('homedata_'.$uid,$data,2);
        }
		return view('admin.index.main',['data'=>$data]);
	}

	/**
	 * 此方法为临时
	 */
	public function user(){
		$data = DB::table('tnet_reginfo')->select('nodeid','nodecode','nodename','photourl','createtime')->whereIn('nodecode',$this->mobile)->get();
		return view('admin.index.user',['data'=>$data]);
	}
	
	// 上传一张图片公共方法 name="image"
	public function upload_image(Request $request){
		$file_path = '';
		base64_upload('images','image',function($data) use(&$file_path){
			$file_path = curl_upfile($data[0]);
		});
		$this->ajax_success('图片上传成功',$file_path);
	}

	/**
	 * 该方法只适用百度webuploder多图片上传插件使用
	 * @param Request $request
	 * @return int|string
	 */
	public function upload(Request $request){
		$file = $request->file('file');
		if($file->isValid()){
			$ext = ['jpeg','jpg','gif','gpeg','png'];
			if(in_array( strtolower($file->extension()),$ext)) {
				$file_path = 'upload/'.date('Y-m-d').'/';
				if(!is_dir($file_path)){
					mkdir($file_path,0777,true);//递归模式
				}
				$extArray = explode('.',$file->getClientOriginalName());
				$extArray = array_reverse($extArray);
				//文件后缀名 $file->extension获取的jpg为jpeg类型
				$extName = strtolower(array_shift($extArray));
				$file_name = date('Ymd') . time() . rand(100000, 999999) . uniqid().'.'.$extName;
				if ($file->move($file_path, $file_name)) {
					$file_path_name =  './'.$file_path.$file_name;
					filedebug($file_path.$file_name);
					$server_path = curl_upfile($file_path_name);
					filedebug($server_path);
					exit('{"jsonrpc" : "2.0", "result" : "上传成功", "id" : "id" ,"url" : "'.$server_path.'"}');
				} else {
					exit('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "上传失败"}, "id" : "id"}');
				}

			}else{
				exit('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "非法类型文件"}, "id" : "id"}');
			}
		}
		exit('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "上传失败"}, "id" : "id"}');
	}

}